from datetime import datetime
from celery import shared_task
from services.upload import git_file_download
from .models import History
from django.conf import settings
from pathlib import Path
import ansible_runner
import celery


class HistoryTask(celery.Task):
    # 任务执行之前，向数据库插入一条任务记录
    def before_start(self, task_id, args, kwargs):
        repo_id, _, user_id = args

        his = History.objects.create(
            repo_id=repo_id,
            task_id=task_id,
            executor_id=user_id,
            status=History.STARTED,
        )
        self.request.history_pk = his.pk

    # 任务执行后，更新任务记录
    def after_return(self, status, retval, task_id, args, kwargs, einfo):
        status_value = getattr(History, status)
        his = History.objects.get(pk=self.request.history_pk)
        his.status = status_value
        his.end_time = datetime.now()
        his.save()


@shared_task(base=HistoryTask)
def run_playbook(repo_id, repo_url, user_id):
    ridh_dir = git_file_download(repo_url, settings.REPO.get("token"))
    playbook_filename = "site.yml"
    if Path(ridh_dir, 'project', 'site.yml').exists():
        playbook_filename = "site.yml"
    elif Path(ridh_dir, 'project', 'site.yaml').exists():
        playbook_filename = "site.yaml"
    elif f := next(Path(ridh_dir, 'project').glob('*.yml'), None):
        playbook_filename = f.name
    elif f := next(Path(ridh_dir, 'project').glob('*.yaml'), None):
        playbook_filename = f.name
    else:
        raise Exception("未找到可以运行的Playbook。运行失败。")
    runner: ansible_runner.Runner = ansible_runner.run(private_data_dir=ridh_dir, playbook=playbook_filename)
    if runner.rc != 0:
        raise Exception("Ansible运行Playbook失败")